/*
 * ============================================================================
 *                   GNU Lesser General Public License
 * ============================================================================
 *
 *
 *
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307, USA.
 * 
 *
 *
 */
package rad.framework.jsf;

import java.util.ArrayList;

import javax.faces.event.PhaseId;
import javax.faces.model.SelectItem;

import rad.framework.cache.ContextScopedCache.EventScopedCache;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.seam.contexts.FacesLifecycle;

/**
 * Cache the calls that hit the database and return select item lists.
 * 
 * @author boudyacho
 */
public abstract class ListCache {

	private static final Log logger = LogFactory.getLog(ListCache.class);

	public Object invoke(Object ctx, String name) {

		if (FacesLifecycle.getPhaseId().equals(PhaseId.APPLY_REQUEST_VALUES)
				|| FacesLifecycle.getPhaseId().equals(
						PhaseId.PROCESS_VALIDATIONS)) {
			return proceed(ctx, name, "Request.");
		}

		if (!FacesLifecycle.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Skip: " + name + " : "
						+ FacesLifecycle.getPhaseId());
			}
			return new ArrayList<SelectItem>();
		}

		return proceed(ctx, name, "Render.");
	}

	protected Object proceed(Object ctx, String methodName, String prefix) {
		EventScopedCache cache = EventScopedCache.instance();
		String key = getClass().getName() + prefix + methodName;
		
		Object result = cache.get(key);
		if (result == null) {
			result = proceed(ctx);
			cache.put(key, result);
			if (logger.isDebugEnabled()) {
				logger.debug("Miss: " + key + " : "
						+ FacesLifecycle.getPhaseId());
			}
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("Hit: " + key + " : "
						+ FacesLifecycle.getPhaseId());
			}
		}
		return result;
	}

	abstract protected Object proceed(Object ctx);
}